import utils from '../../utils/util';
import IM from '../../utils/im';
import config from '../../config';
const PAGE_SIZE = 100;
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    isShow: {
      type: Boolean,
      value: false
    },
    isFullScreen:{
      type:Boolean,
      value:false
    },
    moduleType: {
      type: Number,
      value: 1 //1大班课  2独立直播间（自动添加带货）
    },
    socialRoomId: {
      type: Number,
      value: 0 //社群的id socialRoomId
    },
    liveId: {
      type: Number,
      value: 0
    },
    detailId: { //独立直播用的
      type: Number,
      value: 0
    },
  },
  lifetimes: {
    created: function () {
      this._page = 1;
    },
    attached: function () {}
  },

  /**
   * 组件的初始数据
   */
  data: {
    commerceList: [],
    prodMapType: config.prodMapType,
    prodCourseType: config.prodCourseType,
    relationTypeMap: config.relationTypeMap,
    scrollTop: 0,
    tabIndex:1, // 1商品  2优惠卷
    loadStatus: "", //加载更多
  },

  /**
   * 组件的方法列表
   */
  methods: {
    changeTab(e) {
      let index = e.currentTarget.dataset.index;
      if (index == this.data.tabIndex) return;
      this._page=1;
      this.setData({
        scrollTop: 0,
        tabIndex: index,
        commerceList:[]
      },()=>{
        this._getcommerceList();
      });
     
    },
    onOpen() {
      this._page = 1;
      this.setData({
        commerceList: [],
        loadStatus: "loading"
      }, () => {
        this._getcommerceList();
      })
    },
    refreshData() {
      this.setData({
        scrollTop: 0,
      });
      this.onOpen();
    },
    //获取好物推荐列表
    _getcommerceList() {
      if (this._isRequesting) return;
      this._isRequesting = true;
      let url = '',
        sendData = {
          limit: PAGE_SIZE,
          page: this._page,
          type: this.data.tabIndex
        };
      if (this.data.moduleType == 2) {
        //独立直播间
        url = `social/getLivePersonalGoods/${this.data.socialRoomId}`;
        sendData.moduleType = this.data.moduleType;
        sendData.detailId = this.data.detailId;
      } else {
        //大班课
        url = `social/getBringGoods/${this.data.socialRoomId}`;
      }
      utils.get(url, sendData, false).then(res => {
        if (sendData.type == this.data.tabIndex) {
          if (res.data.length == 0 && this._page == 1) {
            this.setData({
              loadStatus: "none",
            })
          } else if (res.data.length < PAGE_SIZE) {
            this.setData({
              loadStatus: "end"
            })
          } else {
            this.setData({
              loadStatus: ""
            })
          }
          this.data.commerceList = this.data.commerceList.concat(res.data);
          this.setData({
            commerceList: this.data.commerceList
          });
        }
        this._isRequesting = false;
      }).catch(() => {
        this._isRequesting = false;
      })
    },
    //发送好物
    onSendRecommend(e) {
      let item = e.currentTarget.dataset.item;
      let isSend = true;
      console.log("onSendRecommend", item);
      let relationTypeMap = this.data.relationTypeMap;
      if (item.relationType == relationTypeMap.flashSales) {
        //限时购
        if (item.isFlashProd == -1 || item.status == -1 || this._timeCheck(item.endTime)) {
          wx.showToast({
            icon: "none",
            title: '活动已结束',
          })
          isSend = false;
        } else if (!this._timeCheck(item.startTime)) {
          wx.showToast({
            icon: "none",
            title: '活动未开始',
          })
          isSend = false;
        }
      } else if (item.relationType == relationTypeMap.collage || item.relationType == relationTypeMap.coupon || item.relationType == relationTypeMap.shareholderCoupon) {
        //拼团  优惠券  股东优惠券
        if (item.status >= 3 || this._timeCheck(item.endTime)) {
          wx.showToast({
            icon: "none",
            title: '活动已结束',
          })
          isSend = false;
        } else if (item.relationType == relationTypeMap.coupon && item.leftNum <= 0) {
          wx.showToast({
            icon: "none",
            title: '没有剩余产品',
          })
          isSend = false;
        }
      }
      if (!isSend) return;
      let sendData = {
        msgType: 70, //消息类型
        amount: item.amount || item.presale || '', //优惠券满多少元可用
        imgUrl: item.relationType == this.data.relationTypeMap.collage ? item.cover : item.avatar || null, //封面
        subContent: item.prodPrice || null, //价格
        subMsgId: item.id || null,
        subName: item.vipType || null, //活动时间
        subProdType: item.prodType || null,
        subProdId: item.subId || null,
        content: item.name, //当前带货商品名称
        voiceDuration: item.payType, //
        voiceStatus: item.courseType,
        vipInfo: item.vipInfo || null,
        relationId: item.relationId,
        relationType: item.relationType,
        playersPrice: item.playersPrice || null,
        price: item.price || null,
        prodPrice: item.playersPrice || null,
        type: item.type,
        startTime: item.startTime,
        endTime: item.endTime,
        redeemType: item.redeemType,
        pId: item.pId || null,
        courseType: item.courseType,
        validStatus: item.validStatus,
        validPeriod: item.validPeriod || '',
        sort: item.sort,
        version: '20210508',
        atName: item.atName || null,
      }
      if(this.data.detailId){
        sendData.detailId= this.data.detailId
      }
      IM.options.ctx.saveMsgToServer(sendData).then((res) => {
        IM.sendCustomMessage(res);
        IM.options.ctx.addLocalChatMsg(res);
        this.setData({
          isShow: false
        })
      })
    },
    _timeCheck(time) {
      let nowtime = new Date().getTime();
      let couponTime = new Date(time.replace(/-/g, '/')).getTime();
      if (nowtime >= couponTime) {
        return true
      } else {
        return false
      }
    },
    //上下架
    toggleShelves(e) {
      let item = e.currentTarget.dataset.item;
      let idx = e.currentTarget.dataset.index;
      console.log("item", e, idx);
      if(item.bringGoodStatus == 0 && item.stock == 0) return;
      let sendData = {
        moduleType: this.data.moduleType,
        status: item.bringGoodStatus == 1 ? 0 : 1
      };
      sendData.goodsId = item.goodsId;
      if (this.data.moduleType == 2) {
        //独立直播间
        sendData.detailId = this.data.detailId;
      }
      utils.post(`social/changeBringGoodStatus/${this.data.liveId}`, sendData, true).then(res => {
        item.bringGoodStatus = sendData.status
        this.setData({
          ['commerceList[' + idx + ']']: item
        });
        wx.showToast({
          title: sendData.status == 1 ? '已上架！' : '已下架！',
          icon: "none"
        })
      })
    },
  }
})